<template>
  <div class="group-manage">
    <div class="manage-header" style="margin-bottom: 30px;">
      <el-form action="" label-width="80px" label-position="left">
        <el-row>
          <el-col :span="6">
            <el-form-item label="发送人：">
              <el-input v-model="sendFrom" placeholder="请输入发送人" style="width: 200px;" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="接收人：">
              <el-input v-model="receiver" placeholder="请输入接收人" style="width: 200px;" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="内容：">
              <el-input v-model="searchValue" placeholder="请输入想要搜索的内容" style="width: 200px;" size="small" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="时间：">
              <el-date-picker
                v-model="dateTime"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex; justify-content: flex-start;">
            <el-form-item label="">
              <el-button @click="getMessageList()" type="primary" size="small">刷新消息列表</el-button>
              <el-button @click="getMessageList()" type="primary" size="small">搜索</el-button>
              <el-button @click="readAll()" type="primary" size="small">清空未读</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      

    </div>

    <!-- user-namage 高度设置为90%了，这里把table设置为它的90% -->
    <el-table height="90%" :data="tableData" style="width: 100%" v-loading="isLoading">
      <el-table-column prop="sendFrom" label="发送人" width="100"></el-table-column>
      <el-table-column prop="receiver" label="接收人" width="100"></el-table-column>
      <el-table-column prop="messageContent" label="消息内容" width="500">
        <template slot-scope="scope">
          <div v-html="scope.row.messageContent"></div>
        </template>
      </el-table-column>
      <el-table-column prop="readStatus" label="状态" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.readStatus === 'Y'" style="color: green;">已读</span>
          <span v-else style="color: orange;">未读</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发送时间" width="180">
        <template slot-scope="scope">
          <div>{{ formatDate(scope.row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <span style="color: dodgerblue; cursor: pointer;">详情</span>

          <!-- 根据 readStatus 动态显示按钮 -->
          <template v-if="scope.row.readStatus === 'Y'">
            <!-- 如果 readStatus 是 1 (已读)，只显示 "未读" 按钮 -->
            <el-button style="margin-left: 10px;" @click="readMessage(scope.row.id, 'N')" size="small">
              <span style="color: green">置为未读</span>
            </el-button>
          </template>
          <template v-else-if="scope.row.readStatus === 'N'">
            <!-- 如果 readStatus 是 2 (未读)，只显示 "已读" 按钮 -->
            <el-button style="margin-left: 10px;" @click="readMessage(scope.row.id, 'Y')" size="small">
              <span style="color: orange">置为已读</span>
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 固定在底部-->
    <div class="block" style="position: fixed; bottom: 0; width: 100%;">
      <el-pagination background layout="prev, pager, next" :total="totalCount" @current-change="handlePageChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import requestUtil from '../../network/request'
import Cookie from "js-cookie";

export default {
  data() {
    return {
      tableData: [],
      currentPage: 1, // 当前页
      pageSize: 10, // 页大小
      totalPage: 1,
      totalCount: 0,
      searchValue: '',
      sendFrom: '',
      receiver: '',
      messageType: '',
      readStatus: '',
      messageIdList: [],
      isLoading: false,
      dateTime: []
    };
  },
  methods: {
    getMessageList() {
      this.isLoading = true
      requestUtil.post('/message/list', {
        page: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        },
        sendFrom: this.sendFrom,
        receiver: this.receiver,
        messageType: this.messageType,
        readStatus: this.readStatus
      }).then(res => {
        if (res.code === '0') {
          const list = res.result
          // 确保 id 是字符串
          this.tableData = list.map(item => ({
            ...item,
            id: item.id.toString()
          }));
          this.totalCount = res.page ? res.page.totalCount : 0
        } else {
          this.$message.error(res.msg)
        }
        setTimeout(() => {
          this.isLoading = false
        }, 200)
      }).catch(err => {
        setTimeout(() => {
          this.isLoading = false
        }, 200)
      })
    },
    handlePageChange(currentPage) {
      this.currentPage = currentPage
      this.getMessageList()
    },
    readMessage(id, readStatus) {
      // 将单个 id 转换为数组
      const messageIds = Array.isArray(id) ? id : [id];
      requestUtil.post('/message/read', {
        messageIdList: messageIds,
        readStatus: readStatus
      }).then(res => {
        if (res.code === '0') {
          this.$message({
            message: "操作成功",
            type: 'success',
            duration: 200 // 设置显示时间为 600 毫秒（0.6 秒）
          })
          this.getMessageList()
        } else {
          this.$message.error(res.msg)
          //this.$message.error(res.msg, ˜600); // 错误消息也可以设置显示时间
        }
      })
    },
    readAll() {
      const userId = Cookie.get('userId');
      requestUtil.post('/message/readAll', {
        receiver: userId
      }).then(res => {
        if (res.code === '0') {
          this.$message({
            message: "操作成功",
            type: 'success',
            duration: 200 // 设置显示时间为 600 毫秒（0.6 秒）
          })
          this.getMessageList()
        } else {
          this.$message.error(res.msg)
          //this.$message.error(res.msg, ˜600); // 错误消息也可以设置显示时间
        }
      })
    },
    formatDate(timestamp) {
      if (!timestamp) return '';

      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  },
  mounted() {
    this.getMessageList()
  }
};
</script>

<style lang="less" scoped>
.group-manage {
  height: 90%;
  /deep/ .el-form--label-left .el-form-item__label{
    padding-left: 10px;
  }
}
</style>